package net.luoran.dvm.common.util;

import cn.hutool.core.util.IdUtil;
import net.luoran.dvm.entity.ElementGroupDO;
import net.luoran.dvm.entity.SysFileDO;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author: Yu Feifei
 * @since: 2020-10-19 15:04
 * @description:
 * @version: 1.0
 */
public class FileUtil {

    /**
     * 删除单个文件
     *
     * @throws Exception
     */
    public static void deleteFile(SysFileDO sysFile) {
        try {
            String realPath = sysFile.getFilePath();
            File file = new File(realPath);
            if (file.exists()) {
                if (file.isFile()) {
                    file.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param file
     * @throws IOException
     */
    public static Map<String, String> upload(MultipartFile file, String basePath) throws IOException {
        String oldName = file.getOriginalFilename();
        String newName = IdUtil.simpleUUID() + oldName.substring(oldName.indexOf("."));
        File uploadFile = new File(basePath + "/upload/" + newName);
        File parentFile = uploadFile.getParentFile();
        if (!parentFile.exists()) { //创建父目录
            parentFile.mkdirs();
        }
        file.transferTo(uploadFile);
        Map<String, String> resultMap = new HashMap<String, String>();
        resultMap.put("newName", newName);
        resultMap.put("oldName", oldName);
        resultMap.put("path", uploadFile.getAbsolutePath());
        return resultMap;
    }

    /**
     * 下载文件
     *
     * @param id
     * @param response
     * @throws Exception
     */
    public static void download(ElementGroupDO elementGroup, Integer id, HttpServletResponse response) throws
            IOException {
        //从数据库中获取绝对路径
        String realPath = elementGroup.getFileUrl();

        File file = new File(realPath);

        if (!file.exists()) {
            throw new FileNotFoundException();
        }

        byte[] bytes = new byte[1024 * 1024];
        BufferedInputStream bufferedInputStream = null;
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;

        try {
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            //response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(elementGroup.getGroupName(), "UTF-8"));
            outputStream = response.getOutputStream();
            int length;
            while ((length = bufferedInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            outputStream.flush();
        } catch (IOException e) {
            throw new IOException("IO异常");
        } finally {
            if (bufferedInputStream != null) {
                bufferedInputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }

    }

    /**
     * 批量下载并打成zip包
     *
     * @param resumeFileAll
     * @param response
     * @throws IOException
     */
    public static void downloadAll(String zipName, List<ElementGroupDO> resumeFileAll, HttpServletResponse response) throws
            IOException {
        FileInputStream fis = null;
        ZipOutputStream out = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //写入数组中
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            out = new ZipOutputStream(os); //zip文件写到内存中


            File[] resumeFiles = new File[resumeFileAll.size()]; //需要打包的文件数组
            ArrayList<String> oldNameList = new ArrayList<>();
            //创建文件集合
            for (int i = 0; i < resumeFileAll.size(); i++) {
                //resumeFiles[i] = new File(resumeFileAll.get(i).getFilePath());
                //oldNameList.add(resumeFileAll.get(i).getOldName()); ///获取上传时的文件名
            }
            byte[] buff = new byte[1024 * 1024];
            for (int i = 0; i < resumeFiles.length; i++) {
                fis = new FileInputStream(resumeFiles[i]);
                //创建压缩文件中的条目
                ZipEntry entry = new ZipEntry(oldNameList.get(i));
                //将创建好的条目加入到压缩文件中
                out.putNextEntry(entry);
                //写入当前条目所对应的具体内容
                int len = 0;
                while ((len = fis.read(buff)) != -1) {
                    out.write(buff, 0, len);
                }
                out.flush();
            }
            out.close();
            fis.close();

            byte[] bytes = new byte[1024 * 1024];

            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content); //从内存中读取zip文件
            bis = new BufferedInputStream(is);

            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(zipName + ".zip", "UTF-8"));
            bos = new BufferedOutputStream(response.getOutputStream());
            int length;
            while ((length = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, length);
                bos.flush();
            }
            bos.close();
            bis.close();
        } catch (IOException e) {
            throw new IOException("IO异常");
        } finally {
            if (bos != null) {
                bos.close();
            }
            if (bis != null) {
                bis.close();
            }
            if (out != null) {
                out.close();
            }
            if (fis != null) {
                fis.close();
            }
        }

    }

}
